package com.cdqidi.filter;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

public class AuthFilter implements Filter {
	private static Logger logger = Logger.getLogger(AuthFilter.class);
	
	private Set<String> excludesPattern;
	private static final String[] STATICFILTEREXTNAME = {".js", ".css", ".gif", ".png", ".jpg", ".swf",".icon"};

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest)req;
		String requestURI = httpRequest.getRequestURI();
		boolean canFilter = canFilter(requestURI);
		logger.debug("请求地址："+requestURI+",是否需要验证登录： "+canFilter);
		if(canFilter) {
			if(!isLogin(httpRequest)) {
				//判断是否登录，没有登录跳转到错误页面
				req.setAttribute("errmsg", "没有权限访问");
				req.getRequestDispatcher("/WEB-INF/page/error/500.jsp").forward(req, res);
			}
			return;
		}
		chain.doFilter(req, res);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		String exclusions = filterConfig.getInitParameter("exclusions"); 
		String[] _exclusions = exclusions.split(",");
		if(_exclusions.length==1) {
			String exclusion = _exclusions[0];
			if(null==exclusion||"".equals(exclusion)) {
				return;
			}
		}
		excludesPattern = new HashSet<String>(Arrays.asList(_exclusions));
		for (String exclusion : _exclusions) {
			logger.debug("不需要验证权限的地址： "+exclusion);
		}
	}
	
	private boolean isLogin(HttpServletRequest req) {
		Object obj = req.getSession().getAttribute("wPay_user");
		return null==obj?false:true;
	}
	
	
	private boolean canFilter(String requestURI)
	  {
	    for (int i = 0; i < STATICFILTEREXTNAME.length; i++) {
	      if (requestURI.endsWith(STATICFILTEREXTNAME[i]))
	        return false;
	    }
	    if(null==excludesPattern) {
	    	return true;
	    }
	    String lastStr = requestURI.substring(requestURI.length()-1);
	    if(!"/".equals(lastStr)) {
	    	requestURI = requestURI+"/";
	    }
	    requestURI = requestURI.trim();
	    int last=0;
	    for(String excelude:excludesPattern) {
	    	excelude = excelude.trim();
	    	last = excelude.lastIndexOf("*");
	    	if(last>=0) {
	    		excelude = excelude.substring(0, last);
	    		if(requestURI.indexOf(excelude)>-1) {
	    			return false;
	    		}
	    	}else {
	    		if(excelude.equals(requestURI)) {
		    		return false;
		    	}
	    	}
	    }
	    return true;
	  }
	
	@Override
	public void destroy() {
		if(null!=excludesPattern) {
			excludesPattern.clear();
		}
		excludesPattern = null;
	}
}